Duck Types and Protocols
typing.Protocolとは何かを知りたくてこの部分だけ読んだ
https://realpython.com/python-type-checking/#duck-types-and-protocols
例:len関数のtype hint
ref: len()関数がオブジェクトの長さを手にいれる仕組み(PyCon JP 2017)
The answer hides behind the academic sounding term structural subtyping.
One way to categorize type systems is by whether they are nominal or structural:
nominal
In a nominal system, comparisons between types are based on names and declarations.
「nominalなシステムでは、型の比較は名前と宣言に基づく」
The Python type system is mostly nominal, where an int can be used in place of a float because of their subtype relationship.
「Pythonの型システムはほとんどがnominal」
例として「サブタイプ関係により、intはfloatの代わりに使える」
structural
In a structural system, comparisons between types are based on structure.
「structuralなシステムでは、型の比較は構造に基づく」
You could define a structural type Sized that includes all instances that define .__len__(), irrespective of their nominal type.
nominalな型に関わらず、.__len__()を定義する全てのインスタンスを含む構造的な型Sizedを定義できる
https://docs.python.org/ja/3/library/typing.html#typing.Sized
https://docs.python.org/ja/3/library/collections.abc.html#collections.abc.Sized
__len__() メソッドを提供するクラスの ABC です。 (ABC for classes that provide the __len__() method.)
code:typing_len_function.py
from typing import Sized
def len(obj: Sized) -> int:
return obj.__len__()
You can also define your own protocols. This is done by inheriting from Protocol and defining the function signatures (with empty function bodies) that the protocol expects.
「Protocolを継承し、そのプロトコルが期待する関数のシグネチャを(空の関数の本体と一緒に)定義することで、独自のプロトコルを定義できる」
Other examples of protocols 👉 Protocols and structural subtyping (Predefined protocols)